from datetime import datetime

from fastapi import APIRouter, Depends, Request
from pydantic_validation_decorator import ValidateFields
from sqlalchemy.ext.asyncio import AsyncSession

from config.enums import BusinessType
from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_stock.entity.vo.trade_vo import DeleteTradeModel, TradeModel, TradePageQueryModel, UpdateTradeStatusModel
from module_stock.service.trade_executor import get_trade_executor
from module_stock.service.trade_service import TradeService
from module_xtquant.xtdata_subscription_manager import xtdata_subscription_manager
from utils.log_util import logger
from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil
from utils.stock_util import add_stock_suffix

tradeController = APIRouter(prefix='/stock/trade', dependencies=[Depends(LoginService.get_current_user)])


@tradeController.get(
    '/list', response_model=PageResponseModel, dependencies=[Depends(CheckUserInterfaceAuth('stock:trade:list'))]
)
async def get_stock_trade_list(
        request: Request,
        trade_page_query: TradePageQueryModel = Depends(TradePageQueryModel.as_query),
        query_db: AsyncSession = Depends(get_db),
):
    # 获取分页数据
    trade_page_query_result = await TradeService.get_trade_list_services(query_db, trade_page_query,
                                                                         is_page=trade_page_query.is_page)
    logger.info('获取成功')

    if trade_page_query.is_page:
        return ResponseUtil.success(model_content=trade_page_query_result)
    else:
        return ResponseUtil.success(rows=trade_page_query_result)


@tradeController.post('', dependencies=[Depends(CheckUserInterfaceAuth('stock:trade:add'))])
@ValidateFields(validate_model='add_trade')
@Log(title='股票交易任务', business_type=BusinessType.INSERT)
async def add_stock_trade(
        request: Request,
        add_trade: TradeModel,
        query_db: AsyncSession = Depends(get_db),
        current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    add_trade.stock_code = add_stock_suffix(add_trade.stock_code)  # 添加交易所后缀
    add_trade.create_by = current_user.user.user_name
    add_trade.create_time = datetime.now()
    add_trade.update_by = current_user.user.user_name
    add_trade.update_time = datetime.now()
    add_trade_result = await TradeService.add_trade_services(request.app.state.redis, query_db, add_trade)
    logger.info(add_trade_result.message)

    return ResponseUtil.success(msg=add_trade_result.message)


@tradeController.put('', dependencies=[Depends(CheckUserInterfaceAuth('stock:trade:edit'))])
@ValidateFields(validate_model='edit_trade')
@Log(title='股票交易任务', business_type=BusinessType.UPDATE)
async def edit_stock_trade(
        request: Request,
        edit_trade: TradeModel,
        query_db: AsyncSession = Depends(get_db),
        current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    edit_trade.stock_code = add_stock_suffix(edit_trade.stock_code)  # 添加交易所后缀
    edit_trade.update_by = current_user.user.user_name
    edit_trade.update_time = datetime.now()
    edit_trade_result = await TradeService.edit_trade_services(request.app.state.redis, query_db, edit_trade)
    logger.info(edit_trade_result.message)

    return ResponseUtil.success(msg=edit_trade_result.message)


@tradeController.delete('/{ids}', dependencies=[Depends(CheckUserInterfaceAuth('stock:trade:remove'))])
@Log(title='股票交易任务', business_type=BusinessType.DELETE)
async def delete_stock_trade(request: Request, ids: str, query_db: AsyncSession = Depends(get_db)):
    delete_trade = DeleteTradeModel(ids=ids)
    delete_trade_result = await TradeService.delete_trade_services(query_db, delete_trade)
    logger.info(delete_trade_result.message)

    return ResponseUtil.success(msg=delete_trade_result.message)


@tradeController.get(
    '/{id}', response_model=TradeModel, dependencies=[Depends(CheckUserInterfaceAuth('stock:trade:query'))]
)
async def query_detail_stock_trade(request: Request, id: int, query_db: AsyncSession = Depends(get_db)):
    trade_detail_result = await TradeService.trade_detail_services(query_db, id)
    logger.info(f'获取id为{id}的信息成功')

    return ResponseUtil.success(data=trade_detail_result)


@tradeController.put('/status', dependencies=[Depends(CheckUserInterfaceAuth('stock:trade:edit'))])
@ValidateFields(validate_model='update_trade_status')
@Log(title='股票交易任务状态', business_type=BusinessType.UPDATE)
async def update_stock_trade_status(
        request: Request,
        update_status: UpdateTradeStatusModel,
        query_db: AsyncSession = Depends(get_db),
        current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    update_status.update_by = current_user.user.user_name
    update_status.update_time = datetime.now()
    update_result = await TradeService.update_trade_status_services(request.app.state.redis, query_db, update_status)
    logger.info(update_result.message)

    return ResponseUtil.success(msg=update_result.message)


@tradeController.post('/monitor/start', dependencies=[Depends(CheckUserInterfaceAuth('stock:trade:edit'))])
@Log(title='启动交易监控', business_type=BusinessType.UPDATE)
async def start_trade_monitoring(
        request: Request,
        query_db: AsyncSession = Depends(get_db)
):
    """启动交易监控"""
    executor = get_trade_executor()
    await executor.start()
    result = {"success": True, "message": "交易监控已启动"}
    logger.info(f"启动交易监控: {result['message']}")
    return ResponseUtil.success(data=result)


@tradeController.post('/monitor/stop', dependencies=[Depends(CheckUserInterfaceAuth('stock:trade:edit'))])
@Log(title='停止交易监控', business_type=BusinessType.UPDATE)
async def stop_trade_monitoring(
        request: Request,
        query_db: AsyncSession = Depends(get_db)
):
    """停止交易监控"""
    # 清除订阅
    xtdata_subscription_manager().remove_all_subscription()
    # 停止执行器
    executor = get_trade_executor()
    await executor.stop()
    # 停止时也清空所有相关的redis数据
    keys_to_delete = await request.app.state.redis.keys("trade_tasks:*")
    if keys_to_delete:
        await request.app.state.redis.delete(*keys_to_delete)

    result = {"success": True, "message": "交易监控已停止"}
    logger.info(f"停止交易监控: {result['message']}")
    return ResponseUtil.success(data=result)


@tradeController.get('/monitor/status', dependencies=[Depends(CheckUserInterfaceAuth('stock:trade:list'))])
async def get_trade_monitor_status(
        request: Request,
        query_db: AsyncSession = Depends(get_db)
):
    """获取交易监控状态"""
    logger.info("获取交易监控状态")
    executor = get_trade_executor()
    result = {
        "success": True,
        "is_running": executor.get_status(),
    }
    return ResponseUtil.success(data=result)
